<template>
  <div id="rwMap" class="mapContainer"></div>
</template>

<script setup lang="ts">
import { load } from '@2gis/mapgl'
import { propTypes } from '@/utils/propTypes'

const emits = defineEmits(['locateChange'])
const state = reactive({
  lonLat : [],
  config: { properties: { securityJsCode: undefined, apiKey: '' }},
  loading: false,
  //纬度、经度
  locate: {},
  //地图对象
  map: null as any,
  //标记对象
  mapMarker:null as any,
})
const props = defineProps({
  config: propTypes.object.def({}),
  clickMap: propTypes.bool.def(false),
  isWrite: propTypes.bool.def(false),
  locate: propTypes.object.def(undefined),
})

const loadMap = () => {
  state.locate = props.locate

  load().then((mapglAPI) => {
    state.map = new mapglAPI.Map('rwMap', {
      center: [55.31878, 25.23584],
      zoom: 8,
      key: state.config.properties.apiKey,
    })

    if(props.clickMap){
      state.map.on('click', (e) =>{
        console.log(e)
        state.lonLat=e.lngLat
        regeoCode(state.lonLat)
      })
    }

    if (props.locate.latitude && props.locate.longitude) {
      setMarker([Number(props.locate.longitude), Number(props.locate.latitude)])
    }
  })
}

//添加标记点
const setMarker=(lnglat)=> {
  if (lnglat) {
    if (state.mapMarker !== null) {
      // 如果点标记已存在则先移除原点
      state.mapMarker.destroy()
      state.lonLat = []
    }

    load().then((mapglAPI) => {
      state.mapMarker = new mapglAPI.Marker(state.map, {
        coordinates: lnglat,
      })
    })

    state.map.setCenter(lnglat)
    //state.map.setZoom(12)
  }
}

//经纬度转化为地址、添加标记点
const regeoCode=(lonLat)=>{
  if (lonLat) {
    state.locate = { longitude: lonLat[0], latitude: lonLat[1]}
    emits('locateChange', state.locate)
    setMarker(lonLat)
  }
}

watch(() => props.config, (v:any) => {
  state.config = v
  loadMap()
}, { immediate: true })
</script>

<style scoped>
.mapContainer {
  width: 100%;
  height: 240px;
}
</style>
